﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RFIDStockManagement.IDAL;
using System.Data;
using RFIDStockManagement.Model.Public;
using RFIDStockManagement.Common.Public;
using System.Data.Common;

namespace RFIDStockManagement.DAL
{
    /// <summary>
    /// 供应商访问层
    /// </summary>
    sealed class SupplierAccess : BasicAccess, IBasicInfoAccess
    {
        public SupplierAccess()
            : base("rfid_Supplier")
        {
        }

        protected override BasicModelInfo CreateModelInfo(DbDataReader reader)
        {
            SupplierInfo info = null;
            if (reader.Read())
            {
                info = new SupplierInfo();
                int ordinal = reader.GetOrdinal("FID");
                info.Id = reader.GetInt64(ordinal);
                ordinal = reader.GetOrdinal("FName");
                info.Name = reader.GetString(ordinal);
                ordinal = reader.GetOrdinal("FContact");
                info.Contact = reader.GetString(ordinal);
                ordinal = reader.GetOrdinal("FPhone");
                info.Phone = reader.GetString(ordinal);
                ordinal = reader.GetOrdinal("FAddress");
                info.Address = reader.GetString(ordinal);
            }

            return info;
        }

        /// <summary>
        /// 设置被引用信息
        /// </summary>
        /// <param name="info"></param>
        protected override void SetBeQuoteInfo(BasicModelInfo info)
        {
            //如果供应商已经被入库单使用,不允许删除
            DbHelper helper = new DbHelper();
            string sql = string.Format("SELECT TOP 1 1 FROM rfid_InStockbill WHERE FSupplierID={0}", info.Id); ;
            DbCommand comm = helper.GetSqlStringCommand(sql);
            object scalar = helper.ExecuteScalar(comm);
            if (scalar != null)
            {
                info.BeQuote = true;
                info.BeQuoteMessage = "已被入库单引用";
            }
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="info"></param>
        public override BasicModelInfo Save(BasicModelInfo info)
        {
            DbHelper helper = new DbHelper();
            string sql = string.Empty;
            SupplierInfo supplierInfo = info as SupplierInfo;

            sql = string.Format("SELECT TOP 1 1 FROM rfid_Supplier WHERE FID<>{0} AND FName='{1}'", supplierInfo.Id, supplierInfo.Name);
            DbCommand comm = helper.GetSqlStringCommand(sql);
            object scalar = helper.ExecuteScalar(comm);
            if (scalar != null)
            {
                throw new Exception(string.Format("供应商名称“{0}”已经存在！", supplierInfo.Name));
            }
            
            if (supplierInfo.Id <= 0)
            {

                sql = string.Format(@"INSERT INTO rfid_Supplier(FName,FContact,FPhone,FAddress)VALUES('{0}','{1}','{2}','{3}');SELECT @@IDENTITY",
                supplierInfo.Name, supplierInfo.Contact, supplierInfo.Phone, supplierInfo.Address);
                comm = helper.GetSqlStringCommand(sql);
                scalar = helper.ExecuteScalar(comm);
                if (scalar != null)
                {
                    long id = 0;
                    long.TryParse(scalar.ToString(), out id);
                    supplierInfo.Id = id;
                }
            }
            else
            {
                sql = string.Format("UPDATE rfid_Supplier SET FName='{0}',FContact='{1}',FPhone='{2}',FAddress='{3}' WHERE FID={4}",
                    supplierInfo.Name, supplierInfo.Contact, supplierInfo.Phone, supplierInfo.Address, supplierInfo.Id);
                comm = helper.GetSqlStringCommand(sql);
                helper.ExecuteNonQuery(comm);
            }

            return supplierInfo;
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="lstInfo"></param>
        public override List<string> Delete(List<string> lstInfo)
        {
            //如果供应商已经被入库单使用,不允许删除
            List<string> result = new List<string>();
            string sql = string.Format(@"SELECT sp.FID,sp.FName FROM rfid_Supplier sp WHERE
sp.FID IN({0}) AND EXISTS(SELECT TOP 1 1 FROM rfid_InStockbill stock WHERE sp.FID=stock.FSupplierID)", string.Join(",", lstInfo.ToArray()));
            DbHelper helper = new DbHelper();
            DbCommand comm = helper.GetSqlStringCommand(sql);
            using (DbDataReader reader = helper.ExecuteReader(comm))
            {
                while (reader.Read())
                {
                    lstInfo.Remove(reader.GetInt64(reader.GetOrdinal("FID")).ToString());
                    result.Add(string.Format("“{0}”已被入库单引用，不能删除", reader.GetString(reader.GetOrdinal("FName"))));
                }
            }
            if (lstInfo.Count > 0)
            {
                sql = string.Format("DELETE rfid_Supplier WHERE FID IN({0})", string.Join(",", lstInfo.ToArray()));
                comm = helper.GetSqlStringCommand(sql);
                helper.ExecuteNonQuery(comm);
                if (result.Count == 0)
                {
                    result.Add("所选的数据全部删除成功");
                }
                else
                {
                    result.Add("其它所选的数据删除成功");
                }
            }
            
            return result;
        }
    }
}
